import os
import sys
import shutil

def secure_delete_file(filepath, passes=3):
    try:
        # 尝试修改文件权限以确保可写
        try:
            os.chmod(filepath, 0o777)
        except PermissionError:
            pass  # 无权限修改，继续尝试

        with open(filepath, "rb+") as f:
            file_size = os.path.getsize(filepath)
            for _ in range(passes):
                f.seek(0)
                chunk_size = 1024 * 1024  # 1MB
                for i in range(0, file_size, chunk_size):
                    remain = file_size - i
                    current_chunk = min(chunk_size, remain)
                    if _ == 0:
                        data = b'\x00' * current_chunk
                    elif _ == 1:
                        data = b'\xff' * current_chunk
                    else:
                        data = os.urandom(current_chunk)
                    f.write(data)
                f.flush()
                os.fsync(f.fileno())
        os.remove(filepath)
        print(f"Securely deleted file: {filepath}")
    except Exception as e:
        print(f"Error wiping file {filepath}: {e}")

def secure_delete_folder(folderpath, passes=3):
    try:
        # 遍历并安全删除所有文件
        for root, dirs, files in os.walk(folderpath):
            for file in files:
                filepath = os.path.join(root, file)
                secure_delete_file(filepath, passes)
        # 删除目录结构
        shutil.rmtree(folderpath)
        print(f"Securely deleted directory: {folderpath}")
    except Exception as e:
        print(f"Error wiping directory {folderpath}: {e}")

def main():
    if len(sys.argv) < 2:
        print("Usage: python secure_wipe.py <path1> <path2> ...")
        sys.exit(1)

    paths = sys.argv[1:]
    print("警告：此操作将彻底擦除指定文件/目录，无法恢复！")
    print("以下路径将被处理:")
    for path in paths:
        print(f"  - {path}")
    confirm = input("确定继续吗？(y/N): ").lower().strip()
    if confirm != 'y':
        print("操作已取消。")
        sys.exit(0)

    for path in paths:
        if not os.path.exists(path):
            print(f"路径不存在: {path}")
            continue
        # 处理符号链接
        if os.path.islink(path):
            target = os.path.realpath(path)
            print(f"处理符号链接: {path} -> {target}")
            if os.path.exists(target):
                if os.path.isfile(target):
                    secure_delete_file(target)
                elif os.path.isdir(target):
                    secure_delete_folder(target)
                else:
                    print(f"不支持的目标类型: {target}")
            else:
                print(f"目标不存在: {target}")
            try:
                os.unlink(path)
                print(f"已删除符号链接: {path}")
            except Exception as e:
                print(f"删除符号链接失败: {path} - {e}")
        else:
            realpath = os.path.realpath(path)
            if os.path.isfile(realpath):
                secure_delete_file(realpath)
            elif os.path.isdir(realpath):
                secure_delete_folder(realpath)
            else:
                print(f"不支持的文件类型: {realpath}")

if __name__ == "__main__":
    main()
